package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000243.R;
import com.shwread.http.base.Log;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;

import java.lang.reflect.Type;

import logic.bean.RechargeOrderInfo;
import logic.pay.PayResult;
import logic.pay.PayUtil;
import logic.util.Util;
import logic.util.Utils;


/**
 * OrderMenuRechargeActivity
 *
 * @Description：我的——充值界面
 * @Author：zhangdong
 * @Date：2015年7月13日下午15:48:49
 */
public class OrderMenuRechargeActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener {
    private Context context;
    private TextView tvTitle;
    private Button btnBack, btnPay, btnRecord;
    //	private ImageButton        ibRecord;
    private LinearLayout llMoney;
    private EditText etMoney;
    private ImageButton ibUseZhiFuBao;
    private InputMethodManager inputManager;
    private boolean zhifubaoSelected = true;
    private long minLimit = 50;
    private long maxLimit = 50000;
    private RechargeOrderInfo info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.om_recharge);
        this.context = this;
        inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        initView();
        setListener();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PayUtil.SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        OrderMenuRechargeActivity.this.finish();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(context, "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
//													Toast.makeText(context, "支付失败", Toast.LENGTH_SHORT).show();
                            NewActionHelp.closeBalanceRechargeOrder(context, info.getOrderId(), new CloseOrderHandler());
                        }
                    }
                    break;
                }
                case PayUtil.SDK_CHECK_FLAG: {
                    Toast.makeText(context, "是否有支付宝认证账号：" + msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }
    };

    private void setListener() {
        btnBack.setOnClickListener(this);
//		ibRecord.setOnClickListener(this);
        btnRecord.setOnClickListener(this);
        llMoney.setOnClickListener(this);
        ibUseZhiFuBao.setOnClickListener(this);
        btnPay.setOnClickListener(this);
//		etMoney.setOnFocusChangeListener(new OnFocusChangeListener()
//		{
//			
//			@Override
//			public void onFocusChange(View v, boolean hasFocus) {
//				if (!hasFocus)
//				{
//					String text = etMoney.getText().toString().trim();
//					if (com.shwread.httpsdk.util.Util.isNotEmpty(text))
//					{
//						long money = Long.parseLong(text);
//						if (money < minLimit)
//						{
//							etMoney.setText(minLimit + "");
//						}
//					}
//				}
//			}
//		});
        etMoney.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                Editable text = etMoney.getText();
                String value = text.toString().trim();
                if (com.shwread.httpsdk.util.Util.isNotEmpty(value)) {
                    long money = Long.parseLong(value);
                    if (money < minLimit) {
                        btnPay.setEnabled(false);
                    } else {
                        btnPay.setEnabled(true);
                    }
                    if (money > maxLimit) {
                        etMoney.setText(maxLimit + "");
                        text = etMoney.getText();
                        Selection.setSelection(text, text.length()); //使光标置于末尾
                    }
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initView() {
        tvTitle = (TextView) findViewById(R.id.common_header_name);
        tvTitle.setText("充值");
        btnBack = (Button) findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);
//		ibRecord = (ImageButton) findViewById(R.id.picker_image_preview_photos_select);
//		ibRecord.setImageResource(R.drawable.om_ticket_recode);
//		ibRecord.setVisibility(View.VISIBLE);

        llMoney = (LinearLayout) findViewById(R.id.ll_om_recharge_money);
        etMoney = (EditText) findViewById(R.id.et_om_recharge_money);

        ibUseZhiFuBao = (ImageButton) findViewById(R.id.ib_om_recharge_zhifubao);

        btnPay = (Button) findViewById(R.id.btn_om_recharge_pay);
        btnRecord = (Button) findViewById(R.id.btn_om_recharge_record);
        btnPay.setEnabled(false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_back:
                Util.hideInputMethodManager(context, etMoney);
                this.finish();
                break;
//			case R.id.picker_image_preview_photos_select:
//				Util.hideInputMethodManager(context, etMoney);
//				Intent intent = new Intent(context, OrderMenuRechargeRecordActivity.class);
//				startActivity(intent);
//				break;
            case R.id.btn_om_recharge_record:
                Util.hideInputMethodManager(context, etMoney);
                Intent intent = new Intent(context, OrderMenuRechargeRecordActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_om_recharge_money:
                etMoney.setFocusable(true);
                etMoney.setFocusableInTouchMode(true);
                if (etMoney.requestFocus() || etMoney.requestFocusFromTouch())
                    inputManager.showSoftInput(etMoney, InputMethodManager.SHOW_IMPLICIT);
                break;
            case R.id.ib_om_recharge_zhifubao:
                if (zhifubaoSelected) {
                    zhifubaoSelected = false;
                    ibUseZhiFuBao.setBackgroundResource(R.drawable.om_pay_zhifubao_unselected);
                } else {
                    zhifubaoSelected = true;
                    ibUseZhiFuBao.setBackgroundResource(R.drawable.om_pay_zhifubao_selected);
                }
                break;
            case R.id.btn_om_recharge_pay:
                Util.hideInputMethodManager(context, etMoney);
                etMoney.clearFocus();
                clickPay();
                break;
            default:
                break;
        }
    }

    private void clickPay() {
        String money = etMoney.getText().toString();
        if (Util.isEmpty(money)) {
            Utils.showToast(context, "请输入充值金额");
            return;
        }
        if (!zhifubaoSelected) {
            Utils.showToast(context, "请选择支付方式");
        } else {
            pay(money);
        }
    }

    @Override
    public Handler getUIHandler() {
        return handler;
    }

    private void pay(String money) {
        NewActionHelp.newBalanceRechargeOrder(context, Long.parseLong(money) * 100, 1, new GetOrderHandler());
    }

    private class GetOrderHandler
            extends
            ObjectHttpResponseHandler<RechargeOrderInfo> {
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Log.i(responseString);
            if (statusCode < 1000) {
                Utils.ToastShow(context, "网络错误");
            } else {
                Utils.ToastShow(context, "请求出错");
            }
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, RechargeOrderInfo object, String responseString) {
            Log.i(responseString);
            info = object;
//			PayUtil.getSDKVersion(OrderMenuPayMethodActivity.this, getUIHandler());
            //		PayUtil.check(OrderMenuPayMethodActivity.this, getUIHandler());
            String orderInfo;
//			orderInfo = PayUtil.getOrderInfo(object.getOrderSerial(), object.getOrderDesc(), object.getOrderDesc(), money + ".00");
            /** 一分钱测试 */
            orderInfo = PayUtil.getOrderInfo(object.getOrderSerial(), object.getOrderDesc(), object.getOrderDesc(), "0.01");

            PayUtil.pay(OrderMenuRechargeActivity.this, getUIHandler(), orderInfo);
        }

        @Override
        public Type getType() {
            return new TypeToken<RechargeOrderInfo>() {
            }.getType();
        }
    }

    private class CloseOrderHandler
            extends
            ObjectHttpResponseHandler<String> {
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Log.i(responseString);
            if (statusCode < 1000) {
                Utils.ToastShow(context, "网络错误");
            } else {
                Utils.ToastShow(context, "请求出错");
            }
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String object, String responseString) {
            Log.i(responseString);
            Toast.makeText(context, "交易取消", Toast.LENGTH_SHORT).show();
        }

        @Override
        public Type getType() {
            return new TypeToken<String>() {
            }.getType();
        }
    }
}
